<script setup lang='ts'>
import { useUserStore, useChatStore } from '@/stores'
import type { IUser_Login } from '@/api/Auth/type'

const chatStore = useChatStore()
const userStore = useUserStore()
const router = useRouter()

const disabled = ref(false)
const formModel = ref<IUser_Login>({
  username: '',
  password: '',
})
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
})
const formRef = ref()

const onSubmit = async () => {
  await formRef.value.validate()
  disabled.value = true
  try {
    await userStore.login(formModel.value)
    ElMessage.success('登录成功')
    router.push(chatStore.first_chat || '/home/')
  } catch (err) {
    console.error('login error', err)
  } finally {
    disabled.value = false
    formRef.value.resetFields()
  }
}
</script>
<template>
  <div class="login">
    <div class="top">
      <h1>
        <img src="@/assets/images/logo3.jpg" alt="" />
        <span>登录快聊</span>
      </h1>
    </div>
    <div class="bottom">
      <el-form
        autocomplete="off"
        :model="formModel"
        :rules="rules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formModel.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formModel.password"
            type="password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="disabled" @click="onSubmit" type="primary" style="width: 100%"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="desc">
      <span>没有账号？</span>
      <router-link to="/register">立即注册</router-link>
    </div>
  </div>
</template>
<style scoped lang='scss'>
.login {
  width: 400px;
  border: 1px solid #ccc;
  border-radius: 3%;
  box-shadow: 0 0 1px #ccc;
  padding: 30px 50px;
  background-color: #fff;
  .top {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;
    h1 {
      display: flex;
      align-items: center;
      img {
        width: 60px;
        height: 50px;
        object-fit: cover;
        margin-right: 10px;
      }
      span {
        font-size: 20px;
        letter-spacing: 2px;
        font-weight: 500;
      }
    }
  }
  .bottom {
    padding: 0 1px;
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  .desc {
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      margin-right: 10px;
    }
  }
}
</style>